How to add the author filter in WordPress admin

您所在的位置:网站首页 custom post type in wordpress without plugin How to add the author filter in WordPress admin

How to add the author filter in WordPress admin

2023-03-11 02:25| 来源: 网络整理| 查看: 265

Recently, I worked on a project that requested to show all posts for each author. What I did, was to create the author.php and fetched all posts based on the current author slug. I added the ajax pagination as well. Moreover, the requirement requested to show the number of posts that belong to the author as well. So adding the author filter in the WordPress admin will help in rechecking the correct number of posts.

The simple way to add the author filter, you can add the code via functions.php of the active theme. I expect to add to the child theme. Another way, you can add the code via your own plugin.

Note that, if you already configure the parent theme via the customizer, you still can switch to the child theme without losing the customizer configuration by using a helpful plugin.

Now, add the code below to the functions.php

function ar_adding_author_filter( $post_type ) { if( 'books' !== $post_type ) { return; } $selected_author = isset( $_GET[ 'author' ] ) && $_GET[ 'author' ] ? $_GET[ 'author' ] : ''; wp_dropdown_users( array( 'role__in' => array( 'administrator', 'editor', 'author', 'contributor' ), 'name' => 'author', 'show_option_all' => 'All authors', 'selected' => $selected_author ) ); } add_action( 'restrict_manage_posts', 'ar_adding_author_filter' );

In my case, I show the author filter only for the “books” custom post type. So I check the post type before adding the author filter.

You can comment on this post type checking out if you don’t need to.

If you want to show the author filter only on the Posts that belong to the blog page. You can change from “books” to “post” since “post” is a post type of blog page.

Next, I get the query parameter using $_GET. the author is a variable I need to supply to $_GET. I will use this author value in the dropdown list that I am creating below. You can inspect the query parameter by checking the URL at the browser after clicking on the filter button.

After that, I create the users dropdown list using wp_dropdown_users(). It will create the users dropdown list for you. The selected author will be selected in the dropdown list as shown in the code.

Finally, we add our “ar_adding_author_filter” function to the restrict_manage_posts action hook.

That’s it. 🙂

Additionally, if you are looking for adding the custom taxonomy filter in the WordPress admin, check my post.

This post is helpful and saves you time, please consider to buying me a coffee. Keep me awake and write more posts for saving your time.

facebookShare on FacebookTwitterTweet


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3